package com.common.interceptor;

import java.util.Enumeration;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

import com.common.SnsConstants;

import best.spring.framework.web.RequestContext;


public class RequestInterceptor extends HandlerInterceptorAdapter{
	private Logger logger = LoggerFactory.getLogger(RequestInterceptor.class);
	
	
	
	@Override
	public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler)
		    throws Exception {			
		
			logger.info("URI [{}], method [{}], headers [{}]\nparameters [{}]", new String[] { request.getRequestURI(), request.getMethod(), getHeaders(request),
				getParameters(request) });
			RequestContext context = new RequestContext();
			
			request.setAttribute(SnsConstants.REQUEST_CONTEXT, context);
			request.setAttribute(SnsConstants.START_TIME, System.currentTimeMillis());
			
			return true;
		}

		/**
		 * This implementation is empty.
		 */
		public void postHandle(
				HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView)
				throws Exception {
		}

		/**
		 * This implementation is empty.
		 */
		public void afterCompletion(
				HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex)
				throws Exception {
			long start_time = (Long)request.getAttribute(SnsConstants.START_TIME);
			long end_time = System.currentTimeMillis();
			long working_time= end_time - start_time;
			
			RequestContext context= getRequestContext(request);
			
			String resultCode ="0";
			if(context != null){
			}
			logger.info("Status <{}>, WorkingTime [{}], URI [{}]", new String[] {  (context.getResultCode() == null ? resultCode : String.valueOf(context.getResultCode())), String.valueOf(working_time), request.getRequestURI()});
			
		}
		
		/**
		 * 파라미터 가져오기
		 * 
		 * @param request
		 * @return
		 */
		private final String getParameters(HttpServletRequest request) {
			StringBuilder buffer = new StringBuilder();
			Enumeration<?> params = request.getParameterNames();
			while (params.hasMoreElements()) {
				String name = (String) params.nextElement();
				buffer.append(name).append("=\"").append(request.getParameter(name)).append("\"");
				if (params.hasMoreElements())
					buffer.append(", ");
			}
			return buffer.toString();
		}
		
		/**
		 * http header 가져오기
		 * 
		 * @param request
		 * @return
		 */
		private final String getHeaders(HttpServletRequest request) {
			StringBuilder buffer = new StringBuilder();
			Enumeration<?> headers = request.getHeaderNames();
			while (headers.hasMoreElements()) {
				String name = (String) headers.nextElement();
				buffer.append(name).append("=\"").append(request.getHeader(name)).append("\"");
				if (headers.hasMoreElements())
					buffer.append(", ");
			}
			return buffer.toString();
		}
		
		private final RequestContext getRequestContext(HttpServletRequest request) {
			return (RequestContext) request.getAttribute(SnsConstants.REQUEST_CONTEXT);
		}
}
